﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using PmSoft.Core.Extensions;
using PmSoft.Web.Abstractions.Authorization;

namespace PmSoft.Web.Abstractions.Middlewares;

/// <summary>
/// 当前用户中间件，用于处理请求中的用户认证信息
/// </summary>
public class CurrentUserMiddleware : IMiddleware
{
	/// <summary>
	/// JWT服务接口
	/// </summary>
	private readonly IJwtService _jwtService;

	/// <summary>
	/// 日志记录器
	/// </summary>
	private readonly ILogger _logger;

	/// <summary>
	/// 构造函数
	/// </summary>
	/// <param name="jwtService">JWT服务</param>
	/// <param name="logger">日志记录器</param>
	/// <exception cref="ArgumentNullException">当必要的服务为空时抛出</exception>
	public CurrentUserMiddleware(IJwtService jwtService, ILogger<CurrentUserMiddleware> logger)
	{
		_jwtService = jwtService ?? throw new ArgumentNullException(nameof(jwtService));
		_logger = logger ?? throw new ArgumentNullException(nameof(logger));
	}

	/// <summary>
	/// 处理HTTP请求的中间件方法
	/// </summary>
	/// <param name="context">HTTP上下文</param>
	/// <param name="next">请求处理委托</param>
	/// <returns>处理结果的异步任务</returns>
	public async Task InvokeAsync(HttpContext context, RequestDelegate next)
	{
		try
		{
			var jwtToken = context.Request.GetJwtToken();
			if (!string.IsNullOrEmpty(jwtToken))
			{
				context.Items["CurrentUser"] = await _jwtService.ParseTokenAsync(jwtToken);
			}
		}
		catch (Exception ex)
		{
			_logger.LogError(ex, $"Error in CurrentUserMiddleware: {ex.Message}");
		}

		await next(context);
	}
}

/// <summary>
/// 中间件扩展方法类
/// </summary>
public static class MiddlewareExtensions
{
	/// <summary>
	/// 添加当前用户中间件到应用程序管道
	/// </summary>
	/// <param name="builder">应用程序构建器</param>
	/// <returns>配置后的应用程序构建器</returns>
	public static IApplicationBuilder UseCurrentUser(this IApplicationBuilder builder)
	{
		return builder.UseMiddleware<CurrentUserMiddleware>();
	}
}
